'use client'

import { useDrag } from '@/contexts/DragContext'
import { useUserStore } from '@/store/user'
import request from '@/utils/frontend/request'
import {
	LoadingOutlined,
	LockOutlined,
	LogoutOutlined,
	PlusOutlined,
	UserOutlined,
} from '@ant-design/icons'
import {
	Button,
	Card,
	Col,
	Form,
	Input,
	message,
	Modal,
	Popconfirm,
	Row,
	Upload,
	type UploadProps,
} from 'antd'
import { useRouter } from 'next/navigation'
import { useState } from 'react'

interface PasswordForm {
	oldPassword: string
	newPassword: string
	confirmPassword: string
}

export default function ProfilePage() {
	const router = useRouter()
	const { handleMouseDown } = useDrag()
	const { userInfo, setUserInfo, clearUserInfo } = useUserStore()
	const [uploading, setUploading] = useState(false)
	const [passwordModalOpen, setPasswordModalOpen] = useState(false)
	const [passwordForm] = Form.useForm<PasswordForm>()
	const [messageApi, contextHolder] = message.useMessage()

	// 处理头像上传
	const handleAvatarUpload: UploadProps['customRequest'] = async ({ file }) => {
		try {
			setUploading(true)
			const formData = new FormData()
			formData.append('file', file)

			const { data: uploadData } = (await request.post('/common/upload', formData)) as ApiResponse

			// 更新用户头像
			const { data: userData } = (await request.patch(`/user/${userInfo?.id}`, {
				avatar: uploadData,
			})) as ApiResponse

			setUserInfo({ ...userInfo!, avatar: uploadData })
			messageApi.success('头像更新成功')
		} catch (error) {
			messageApi.error('头像上传失败')
		} finally {
			setUploading(false)
		}
	}

	// 处理密码修改
	const handlePasswordChange = async (values: PasswordForm) => {
		try {
			if (values.newPassword !== values.confirmPassword) {
				messageApi.error('两次输入的密码不一致')
				return
			}

			const { message: msg } = (await request.patch(`/user/${userInfo?.id}/password`, {
				oldPassword: values.oldPassword,
				newPassword: values.newPassword,
			})) as ApiResponse

			messageApi.success(msg)
			setPasswordModalOpen(false)
			passwordForm.resetFields()
		} catch (error) {
			messageApi.error('修改密码失败')
		}
	}

	// 处理退出登录
	const handleLogout = async () => {
		try {
			// 调用退出接口
			const { message, success } = (await request.post('/auth/logout')) as ApiResponse

			if (success) {
				// 断开 WebSocket 连接
				// disconnectWebSocket()

				// 清除本地存储的用户信息
				clearUserInfo()

				// 显示退出成功提示
				messageApi.success(message)

				// 延迟跳转到登录页
				setTimeout(() => {
					router.push('/login')
					router.refresh()
				}, 500)
			}
		} catch (error) {
			messageApi.error(error as string)
		}
	}

	return (
		<div className="h-full flex flex-col">
			{contextHolder}
			{/* 标题区域 */}
			<div className="h-20 px-8 border-b border-gray-700 flex items-center">
				{/* 左侧标题区域 - 可拖拽 */}
				<div
					className="flex-1 h-full flex items-center cursor-grab active:cursor-grabbing"
					onMouseDown={handleMouseDown}
				>
					<h1 className="text-2xl font-bold select-none">个人中心</h1>
				</div>

				{/* 右侧退出按钮 */}
				<Popconfirm
					title="退出确认"
					description="确定要退出系统吗？"
					okText="确认"
					cancelText="取消"
					onConfirm={handleLogout}
				>
					<Button type="text" danger icon={<LogoutOutlined />}>
						退出系统
					</Button>
				</Popconfirm>
			</div>

			{/* 主内容区域 */}
			<div className="flex-1 p-8 overflow-y-auto">
				<Row gutter={24}>
					{/* 用户信息看板 */}
					<Col span={8}>
						<Card>
							<div className="flex flex-col items-center">
								<Upload
									name="avatar"
									listType="picture-circle"
									showUploadList={false}
									customRequest={handleAvatarUpload}
									className="!w-32 !h-32"
									beforeUpload={(file) => {
										const isImage = file.type.startsWith('image/')
										if (!isImage) {
											messageApi.error('只能上传图片文件!')
										}
										const isLt5M = file.size / 1024 / 1024 < 5
										if (!isLt5M) {
											messageApi.error('图片大小不能超过 5MB!')
										}
										return isImage && isLt5M
									}}
								>
									{userInfo?.avatar ? (
										<img
											src={userInfo.avatar}
											alt="avatar"
											className="w-full h-full rounded-full object-cover"
										/>
									) : (
										<div>
											{uploading ? <LoadingOutlined /> : <PlusOutlined />}
											<div className="mt-2">更换头像</div>
										</div>
									)}
								</Upload>
								<h2 className="text-xl font-medium mt-4">{userInfo?.nickname}</h2>
								<p className="text-gray-500">{userInfo?.username}</p>
							</div>
							<div className="mt-6">
								<p>
									<UserOutlined className="mr-2" />
									角色：{userInfo?.role === 'admin' ? '管理员' : '普通用户'}
								</p>
								<p>
									<LockOutlined className="mr-2" />
									状态：<span className="text-green-500">在线</span>
								</p>
							</div>
						</Card>
					</Col>

					{/* 个人信息编辑 */}
					<Col span={16}>
						<Card title="账号安全">
							<div className="flex items-center justify-between p-4 border-b">
								<div>
									<h3 className="font-medium">登录密码</h3>
									<p className="text-gray-500 text-sm">建议定期更换密码，确保账号安全</p>
								</div>
								<Button type="primary" onClick={() => setPasswordModalOpen(true)}>
									修改密码
								</Button>
							</div>
						</Card>
					</Col>
				</Row>
			</div>

			{/* 修改密码弹窗 */}
			<Modal
				title="修改密码"
				open={passwordModalOpen}
				onOk={() => passwordForm.submit()}
				onCancel={() => {
					setPasswordModalOpen(false)
					passwordForm.resetFields()
				}}
			>
				<Form form={passwordForm} layout="vertical" onFinish={handlePasswordChange}>
					<Form.Item
						name="oldPassword"
						label="当前密码"
						rules={[{ required: true, message: '请输入当前密码' }]}
					>
						<Input.Password />
					</Form.Item>
					<Form.Item
						name="newPassword"
						label="新密码"
						rules={[{ required: true, message: '请输入新密码' }]}
					>
						<Input.Password />
					</Form.Item>
					<Form.Item
						name="confirmPassword"
						label="确认新密码"
						rules={[{ required: true, message: '请再次输入新密码' }]}
					>
						<Input.Password />
					</Form.Item>
				</Form>
			</Modal>
		</div>
	)
}
